# usagestats.py
# Original Author: Amar Zumkhawala (amarzumkhawala@gmail.com)
# Project URL - http://code.google.com/p/feedflare-categories
# Distributed under Apache License 2.0
#
# $Revision: 34 $, $Date: 2009-01-12 19:30:57 +0000 (Mon, 12 Jan 2009) $
# $Author: amarzumkhawala $

import logging
import datetime

from google.appengine.ext import db
from urlparse import urlparse

#
# Model for usage statistics logging
#

"""Usage: a model that keeps track of the number of times each blog queries us,
   per blog post, per day."""
class Usage(db.Model):
  url = db.LinkProperty(required=True)
  date = db.DateProperty()
  requestCount = db.IntegerProperty()
  atomIds = db.StringListProperty()

"""The usage statistics service class logs usage of the service"""
class UsageStatisticsService:
  def record(self, atomId, blogurl):
    ##
    # update db tables
    ##
    url = urlparse(blogurl)
    domainUrl = "http://"+url.hostname+"/"

    logging.debug(atomId + "->" + domainUrl)

    # update the daily summary entity for the blog
    today = datetime.date.today() 

    ds = Usage.get_or_insert(domainUrl + str(today), 
                             url=db.Link(domainUrl),
                             date=today,
                             requestCount=0)
    key = ds.key()
    ds = db.run_in_transaction(increment_usage, key, atomId)

    logging.debug("requestCount = %d", ds.requestCount)
    # done with logging usage statistics to db!

"""Method to run within a db transaction that updates the daily ds request count"""
def increment_usage(key,atomId):
  ds = Usage.get(key)
  ds.requestCount += 1
  if (ds.atomIds.count(atomId) == 0):
    ds.atomIds.append(atomId)
  ds.put()
  return ds
